#ifndef OPENCCUTIL_H
#define OPENCCUTIL_H

#include <QObject>
#include <QLibrary>
#include <QMutex>
#include <QString>

// typedef 一下核心指针
typedef void* (*OpenCC_Create)(const char* configPath);
typedef char* (*OpenCC_ConvertUTF8)(void* opencc, const char* input, size_t length);
typedef void (*OpenCC_Destroy)(void* opencc);
typedef void (*OpenCC_Free)(char* str);

class OpenCCUtil : public QObject
{
    Q_OBJECT
    Q_DISABLE_COPY_MOVE(OpenCCUtil)	// 禁止移动拷贝

public:
	// 转换方向
	enum class ConvertDirection {
        S2T_TW,  // 简体→台湾繁体
        S2T_HK,  // 简体→香港繁体
        T2S      // 繁体→简体
    };

	// 单例
	static OpenCCUtil* getInstance(QObject* parent = nullptr);
    ~OpenCCUtil() override;

	// func
	QString convert(const QString& text, ConvertDirection direction);
	void setDictPath(const QString& path);

	QString getDictPath() const { return m_dictPath; }
	bool isInitialized() const { return m_isInitialized; }

signals:
    void initFailed(const QString& errorMsg);

private:
	explicit OpenCCUtil(QObject* parent = nullptr);
	// helper
	bool initOpenCC();												// 初始化OpenCC库（动态加载dll）
    QString getConfigPathByDirection(ConvertDirection direction);	// 根据转换方向获取配置文件路径
    bool validateDictPath(const QString& path);						// 校验词典路径有效性
	
private:
    static OpenCCUtil* m_instance;
    static QMutex m_instanceMutex;

	// OpenCC库相关
    QLibrary m_openccLib;                // 动态库实例
    OpenCC_Create m_openccCreate;        // 创建OpenCC实例函数
    OpenCC_ConvertUTF8 m_openccConvert;  // 转换函数
    OpenCC_Destroy m_openccDestroy;      // 销毁实例函数
    OpenCC_Free m_openccFree;            // 释放转换结果函数
    bool m_isInitialized = false;        // 初始化状态

    // 词典路径
    QString m_dictPath;                  // 用户配置路径
    const QString m_defaultDictPath = "thirdparty/opencc/data/";  // 默认路径
    // 转换方向→配置文件映射
    QMap<ConvertDirection, QString> m_dirToConfig = {
        {ConvertDirection::S2T_TW, "s2t.json"},
        {ConvertDirection::S2T_HK, "s2hk.json"},
        {ConvertDirection::T2S, "t2s.json"}
    };

};


#endif	// OPENCCUTIL_H